package day05

import scala.actors.Actor
import scala.util.Random

/**
  * 用Actor实现同步和异步的消息的发送和消息的接收
  */
class ActorDemo3 extends Actor{
  override def act(): Unit = {
    while(true){
      //偏函数
      receive{
        case "start" => println("starting...")
        case AsynMsg(id,msg) => {
          println(s"id:$id,AysnMsg:$msg")
          Thread.sleep(2000)
          sender ! ReplyMsg(Random.nextInt(10),"Aysn success")
        }
        case SynMsg(id,msg) =>{
          println(s"id:$id,SyncMsg:$SynMsg")
          Thread.sleep(2000)
          sender ! ReplyMsg(Random.nextInt(10),"Sync success")
        }
      }
    }
  }
}

object ActorDemo3{
  def main(args: Array[String]): Unit = {
    val actorDemo3 = new ActorDemo3
    actorDemo3.start()
    //异步发送消息，没有返回值
    actorDemo3 ! AsynMsg(Random.nextInt(10),"Hi~ Honey")
    println("send Asyn message ,no return value")

    //同步发送消息，线程等待有返回值
    val content: Any = actorDemo3 !? SynMsg(Random.nextInt(10),"Hi~ Tod")
    println("send Syn message ,have return value")
    println(content)

    //异步发送消息，有返回值，返回类型是Future[Any]
    val reply: actors.Future[Any] = actorDemo3 !! AsynMsg(3,"Hi~ ningning")
   // Thread.sleep(5000)
    if(reply.isSet){
      println(reply.apply())
    }else{
      println("None")
    }
  }
}

case class AsynMsg(id:Int,msg:String)
case class SynMsg(id:Int,msg:String)
case class ReplyMsg(id:Int,msg:String)